﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using mshtml;
using System.Reflection;
using System.Windows.Forms;


namespace Weibo2Sfdc
{
    class WBAutoLogin
    {

        public void AutoLoginWeibo( WebBrowser web_main)
        {
            try
            {
                if (web_main.Url.ToString() == "http://weibo.com/login")
                {
                    //MessageBox.Show("开始登陆 : " + web_main.Url);
                    String encodePwdCmd = "var wb_user_key = sinaSSOEncoder.base64.encode('" + Properties.Settings.Default.WeiboUsername + "')";
                    //MessageBox.Show(encodePwdCmd);

                    IHTMLDocument2 vDocument = web_main.Document.DomDocument as IHTMLDocument2;

                    IHTMLWindow2 vWindow = (IHTMLWindow2)vDocument.parentWindow;

                    vWindow.execScript(encodePwdCmd, "JavaScript");

                    Object user_key = vWindow.GetType().InvokeMember(
                                                  "wb_user_key", BindingFlags.GetProperty,
                                                   null, vWindow, new object[] { }
                                            );
                    MessageBox.Show(Properties.Settings.Default.WeiboUsername + " : " + user_key.ToString());

                    String login_url = "https://login.sina.com.cn/sso/login.php?entry=weisousuo";
                    login_url += "&su=" + user_key;
                    login_url += "&sp=" + Properties.Settings.Default.WeiboPassword;
                    login_url += "&url=http://weibo.com/login.php?url=http%3A%2F%2Fs.weibo.com%2F";

                    web_main.Navigate(login_url);
                }
                else
                {
                    web_main.Navigate("http://weibo.com/login");
                    this.AutoLoginWeibo( web_main );
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }



    }
}
